﻿package net.wangit.framework.expression;

import net.wangit.context.ActionContext;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
/**
 * Request表达式
 * @author watson
 *
 */
public class RequestExpression {

	private static final String PREFIX = "$R{";
	private static final String SUFFIX = "}";

	public RequestExpression() {
	}

	public static final String resolve(ActionContext ac, String expression) {
		return resolve(ac, expression, "", true);
	}

	protected static final String resolve(ActionContext ac, String expression,
			String defaultValue, boolean emptyValid) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression,
				RequestExpression.PREFIX, RequestExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					RequestExpression.PREFIX)).append(attribute).append(
					RequestExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(ac, attribute, defaultValue, emptyValid));
			expression = expression.substring(index + attribute.length()
					+ RequestExpression.PREFIX.length()
					+ RequestExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	private static String getValue(ActionContext ac, String attribute,
			String defaultValue, boolean emptyValid) {
		if (emptyValid) {
			return ac.getRequestParameter(attribute, defaultValue);
		} else {
			String value = ac.getRequestParameter(attribute);
			return Checker.isEmpty(value) ? defaultValue : value;
		}
	}
}
